<?php

namespace App\Http\Middleware;

use App\Http\Controllers\AdminController;
use App\Models\Role;
use Closure;
use Illuminate\Support\Facades\Auth;

class ManageAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!Auth::check()) {
            return redirect("/manage/login");
        }
        // 给用户添加权限
        if(auth()->user()->role != 0){
            $user_role = Role::findOrFail(auth()->user()->role);
            session()->put('user_role',$user_role);
            session()->put('keyword','');
            if(!empty(request()->route()->getAction()['as'])){
                $action_url = request()->route()->getAction()['as'];
                $actions = explode(".",$action_url);
                $controller = "";
                if(strpos($action_url,".") === false){
                    $action = $actions[0];
                }else{
                    $controller = $actions[0];
                    $action = $actions[1];
                }
                AdminController::check_purview($controller,$action);
            }
        }

        $menus = AdminController::getMenu();
        session()->put('menu',$menus);
        return $next($request);
    }
}
